

// pub fn count_provinces() -> String {
// }
use std::collections::{HashMap, HashSet,BTreeMap};
use std::fs;

pub fn count_provinces() -> String {
    // 读取并解析文件
    let cities_content = fs::read_to_string("cities.txt").unwrap();
    let district_content = fs::read_to_string("district.json").unwrap();
    let district: HashMap<String, HashMap<String, Vec<String>>> = serde_json::from_str(&district_content).unwrap();

    // 创建省份-城市映射
    let mut province_cities: HashMap<String, Vec<String>> = HashMap::new();
    
    // 解析cities.txt，按行处理
    for line in cities_content.lines() {
        let parts: Vec<&str> = line.trim().split('　').collect();
        if parts.len() < 2 {
            continue;
        }
        
        let province = parts[0].trim().replace("省", "").replace("市", "");
        let cities: Vec<String> = parts[1..].iter()
            .map(|&city| city.trim().replace("市", "").replace("区", ""))
            .filter(|city| !city.is_empty())
            .collect();
            
        province_cities.insert(province, cities);
    }

    // 使用BTreeMap来保证按key排序
    let mut sorted_results: BTreeMap<String, usize> = BTreeMap::new();
    
    for (group_id, cities_map) in district.iter() {
        let mut provinces = HashSet::new();
        
        // 遍历district中的每个城市
        for city_name in cities_map.keys() {
            // 检查每个城市属于哪个省份
            for (province, cities) in &province_cities {
                if cities.contains(&city_name.replace("市", "")) {
                    provinces.insert(province.clone());
                }
            }
        }
        
        sorted_results.insert(group_id.clone(), provinces.len());
    }

    // 构建结果字符串
    let result: String = sorted_results
        .iter()
        .map(|(_group_id, count)| format!("{}", count))
        .collect::<Vec<String>>()
        .join(",");

    result
}